<?php
/**
 * Description: 题库搜索
 * User: lizhen
 * Date: 16/9/7
 * Time: 11:49
 */

require LIB_DIR . '/AliyunOpenSearch.class.php';

class SearchQuestion implements iController{

    const SEARCH_TYPE_QUESTION = 1; //题目
    const SEARCH_TYPE_MATERIAL = 2; //材料
    const SEARCH_TYPE_OPTIONS = 3; //选项
    const SEARCH_TYPE_ANALYSIS = 4; //解析
    const SEARCH_TYPE_ALL = 9; //包括以上所有

    /**
     * 题库搜索
     * @ 示例： /quizbank/search_question?search=1&keywords=学生&offset=2&count=3
     * @param array $queryArgs  search（搜索字段）: ↑参考常量;   keywords（关键词）: 例:学生; offset（起始位置）; count（数量）;
     * @return null|array()
     */
    public function output($queryArgs) {

        if (!empty($queryArgs['search']) && !empty($queryArgs['keywords'])) {
            global $cmsdb;

            $searchTypeName = $this->_getSearchTypeName($queryArgs['search']);
            if (empty($searchTypeName))
                return genOutput(1000);

            $keywords = trim(str_replace(',', '，', $queryArgs['keywords']));
            $offset = !empty($queryArgs['offset']) ? intval($queryArgs['offset']) : 0;
            $count  = !empty($queryArgs['count']) ? intval($queryArgs['count']) : 30;
            if ($count > 30)
                $count = 30;

            $os = new AliyunOpenSearch();
            $data =  $os->from(AliyunOpenSearch::DATA_QUESTIONS)
                        ->search($searchTypeName , str_replace('.', ' ', $keywords))
                        ->filter('type', 1)
                        ->limit($offset ,$count)
                        ->exec();

            $ids = [];
            $keywordsArr = [];
            foreach ($data->items as $k => $v) {
                $ids[] = ($v->id);
                //抓取关键词
                preg_match_all('/<kw>(.*?)<\/kw>/is', $v->question.$v->options.$v->material, $array);
                $keywordsArr = array_merge($keywordsArr,array_unique($array[1]));
            }

            $keywordsArr[] = $keywords;
            $keywordsArr = array_values(array_unique($keywordsArr));

            $questionData = getQuestionsByIds($ids);
            $list = [];
            $materialIds = [];
            foreach ($questionData as $questionDataKey => $questionDataValue) {
                if ($questionDataValue['material_id'] == 0) {
                    $questionDataValue['type'] = 'question';
                    $list[] = $questionDataValue;
                } else {
                    if (!in_array($questionDataValue['material_id'],$materialIds)) {
                        $materialIds[] = $questionDataValue['material_id'];
                        $questionIds  = [];
                        $materialData = [];
                        $sql = 'SELECT `id`  FROM `original_ztk_questions` WHERE material_id = '.$questionDataValue['material_id'];
                        $questions = $cmsdb->getResults($sql);
                        foreach ($questions as $questionsKey => $questionsValue) {
                            $questionIds[] = $questionsValue->id;
                        }
                        $materialData['type']      = 'material';
                        $materialData['questions'] = getQuestionsByIds($questionIds);
                        $list[] = $materialData;
                    }
                }
            }

            return genOutput( 1,array(
                'response_code' => 1,
                'keywords' => $keywordsArr,
                'total' => $data->total,
                'list' => $list,
            ));
        }
        return genOutput(1000);
    }

    /**
     * 获取搜索字段名称
     * @param $SearchType
     * @return null|string
     */
    private function _getSearchTypeName($SearchType) {
        switch ($SearchType) {
            case self::SEARCH_TYPE_QUESTION:
                $searchTypeName = 'question';
                break;
            case self::SEARCH_TYPE_MATERIAL:
                $searchTypeName = 'material';
                break;
            case self::SEARCH_TYPE_OPTIONS:
                $searchTypeName = 'options';
                break;
            case self::SEARCH_TYPE_ANALYSIS:
                $searchTypeName = 'analysis';
                break;
            case self::SEARCH_TYPE_ALL:
                $searchTypeName = 'all';
                break;
            default:
                $searchTypeName = null;
        }
        return $searchTypeName;
    }
}



